import React, { useEffect, useMemo, useState, useRef } from "react";
import ajax from "@/services";
import { echartTypes } from "@/config/character";
import { FormSelect, ResultWrap } from "@/components";
import { SketchPicker } from 'react-color'

let cfg = {
  // radius should be small ONLY if scaleRadius is true (or small radius is intended)
  // if scaleRadius is false it will be the constant radius used in pixels
  "radius": 2,  //半径
  "maxOpacity": .8, // 最大透明度
  // scales the radius based on map zoom
  "scaleRadius": true, // 设置热力点是否平滑过渡
  // if set to false the heatmap uses the global maximum for colorization
  // if activated: uses the data maximum within the current map boundaries
  //   (there will always be a red spot with useLocalExtremas true)
  "useLocalExtrema": true, //使用局部极值
  // which field name in your data represents the latitude - default "lat"
  latField: 'lat', // 纬度字段
  // which field name in your data represents the longitude - default "lng"
  lngField: 'lng', // 经度字段
  // which field name in your data represents the data value - default "value"
  valueField: 'value', // 值字段
  gradient: { 0.25: "rgb(0,0,255)", 0.55: "rgb(0,255,0)", 0.85: "yellow", 1.0: "rgb(255,0,0)"}, //热度默认颜色值，从外到里的颜色
  // gradient: { 0.25: "rgb(0,255,128)", 0.55: "rgb(0,255,255)", 0.85: "rgb(0,128,255)", 1.0: "blue" } //此处为设置颜色
};
let map;
var heatmapLayer;
// var chart_type = "地图热力图";
export default function Heatmap(props) {
  const { type = "6" } = props;

  const [loading, setLoading] = useState(true);
  // 全部柱状图数据
  const [data, setData] = useState([]); // 下拉地图数据
  const [currentData, setCurrentData] = useState({});
  const [fields, setFields] = useState([]); // 下拉属性字段，数值类型
  const [currentField, setCurrentField] = useState({}); // 下拉属性字段，数值类型
  const mapRef = useRef(null);

  const [defaultColors, setDefaultColors] = useState([
    {id:'默认1', name:'色带1', data:['rgb(0,0,255)', 'rgb(0,255,0)', 'yellow', 'rgb(255,0,0)']},
    {id:'默认2', name:'色带2', data:['rgb(0,255,128)', 'rgb(0,255,255)', 'rgb(0,128,255)', 'blue']},
    {id:'默认3', name:'色带3', data:['rgb(0,0,255)', 'rgb(0,255,0)', 'blue', 'rgb(255,0,0)']},
    {id:'默认4', name:'色带4', data:['#213660', '#394e61', '#445e79', '#506e9d', '#85a0bd', '#dae5eb', '#f9f7f2', '#faebe2','#d8b599', '#d0ac98',  '#c16e5c', '#7a3238', '#542029']}
  ])

  const [currentColor, setCurrentColor] = useState(
    {id:'默认1', name:'色带1', data:['rgb(0,0,255)', 'rgb(0,255,0)', 'yellow', 'rgb(255,0,0)']}
  )

  const getData = () => {
    // setLoading(true);
    let chart_type = echartTypes.filter((item) => item.value === type)[0]?.label || "";

    ajax
      .getFileList({ chart_type, }, false)
      .then(
        (res) => {

          const heatmapData = res.data.filter(d => d.chart_type === chart_type && d.data.length)

          let findItem = heatmapData.filter((item) => item.is_default == 1)[0] || data[0];
          console.log(heatmapData, findItem)
          setCurrentData(findItem);
          let fields = []
          Object.keys(findItem.data[0] || []).forEach(it => {
            if (!(['lng', 'lat', 'id', 'data_id', 'name', 'value'].includes(it))) {
              fields.push({
                id: it,
                name: it,
              })
            }
          })
          setFields(fields);
          setCurrentField(fields[0]);
          setData(heatmapData);

        },
        (err) => {
          setData([]);
        }
      )
      .finally(() => {
        // setLoading(false);
      });
  };

  useEffect(() => {
    getData();

    map = L.map(mapRef.current, {
      crs: L.CRS.EPSG4326,
      center: [32.85, 120.35],
      zoom: 13
    });
    window.hmap = map;
    var activeDraw = false; // 全局参数,是否正在画线
    const VEC_C = 'http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
    const CVA_C = 'http://t1.tianditu.com/cva_c/wmts?layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
    const keys = ['0db778f3a181108e2cbb155d495fc774', 'bc7199b502d057ad5be9712329bcdbad'];
    const TK_KEY = keys[parseInt((Math.random() * keys.length))]; 
    L.tileLayer(VEC_C + TK_KEY, {
      maxZoom: 20,
      tileSize: 256,
      zoomOffset: 1,
    }).addTo(map);
    L.tileLayer(CVA_C + TK_KEY, {
      maxZoom: 20,
      tileSize: 256,
      zoomOffset: 1,
    }).addTo(map);


    heatmapLayer = new HeatmapOverlay(cfg);

    heatmapLayer.addTo(map)

    return () => {
    }
  }, [])


  // 更新地图
  useEffect(() => {
    if (Object.getOwnPropertyNames(currentData).length === 0 || Object.getOwnPropertyNames(currentField).length === 0) return;

    var testData = {
      max: 8,
      data: currentData.data.map(it=>{
        return {
          ...it,
          value: it[currentField.id] // 根据value进行渲染
        }
      })
    };
    cfg.gradient = {
      0.25: currentColor.data[0],
      0.55: currentColor.data[1],
      0.85: currentColor.data[2],
      1: currentColor.data[3]
    }

    map.removeLayer(heatmapLayer)
    heatmapLayer = new HeatmapOverlay(cfg);
    heatmapLayer.addTo(map)
    heatmapLayer.setData(testData);
    // 缩放到当前
    var features = turf.featureCollection(currentData.data.map(it=>{
      return turf.point([it.lng, it.lat])
    }));
    
    var enveloped = turf.envelope(features);

    map.fitBounds([[enveloped.bbox[1], enveloped.bbox[0]],[enveloped.bbox[3], enveloped.bbox[2]]])

  }, [currentData, currentField, currentColor])

  const handleChangeComplete = (color) => {
    console.log({ background: color.hex });
  };

  return (
    <div className="echart-com-container" style={{ padding: "10px" }}>
      <div className="title-header">
        {/* <a className="file-name" target="_blank" href={currentData.file_path} download>
          {currentData.file_name || "-"}
        </a> */}
        <FormSelect
          className="select-box"
          placeholder="切换文件"
          options={data}
          allowClear={false}
          value={currentData.id}
          onChange={(v) => {
            const findItem = data.find((item) => item.id === v);
            setCurrentData(findItem);
            let fields = []
            Object.keys(findItem.data[0]).forEach(it => {
              if (!(['lng', 'lat', 'id', 'data_id', 'name', 'value'].includes(it))) {
                fields.push({
                  id: it,
                  name: it,
                })
              }
            })
            setFields(fields);
            setCurrentField(fields[0]);
          }}
          style={{ width: 150 }}
          fieldNames={{ value: "id", label: "file_name" }}
        />
        <FormSelect
          className="select-box"
          placeholder="切换属性"
          options={fields}
          allowClear={false}
          value={currentField.id}
          onChange={(v) => {
            setCurrentField({ id: v, name: v });
          }}
          style={{ width: 100 }}
          fieldNames={{ value: "id", label: "name" }}
        />
        <FormSelect
          className="select-box"
          placeholder="切换色带"
          options={defaultColors}
          allowClear={false}
          value={currentColor.id}
          onChange={(v) => {
            const item = defaultColors.find(c => c.id === v);
            setCurrentColor({ ...item });
          }}
          style={{ width: 100 }}
          fieldNames={{ value: "id", label: "name" }}
        />
         {/* <SketchPicker
            color={currentColor.data[1]}
            onChangeComplete={ handleChangeComplete }
        />
        <SketchPicker
            value={currentColor.data[1]}
            allowClear
            onChange={(c) => {
              console.log(c.toHexString());
            }}
          />
        <SketchPicker
            value={currentColor.data[2]}
            allowClear
            onChange={(c) => {
              console.log(c.toHexString());
            }}
          />
        <SketchPicker
            value={currentColor.data[3]}
            allowClear
            onChange={(c) => {
              console.log(c.toHexString());
            }}
          /> */}
      </div>
      <div className="echart-body">
        <ResultWrap >
          <div ref={mapRef} style={{ width: '100%', height: '100%' }}></div>
        </ResultWrap>
      </div>
    </div>
  );
}
